<template lang="pug">
.view.cp-credential-man-provider.fix-flex-pos
  el-form.cl-search(:inline="true")
    el-form-item(label="类别 : ")
      el-select(v-model="providerCate", placeholder="请选择", style="width: 120px")
        el-option(v-for="item in vendorCateSelectAll", :key="item.value", :label="item.name", :value="item.value")
    el-form-item(label="分级 : ")
      el-select(v-model="providerGrade", placeholder="请选择", style="width: 120px")
        el-option(v-for="item in vendorGradeSelectAll", :key="item.value", :label="item.name", :value="item.value")
    el-form-item(label="状态 : ")
      el-select(v-model="providerStatus", placeholder="请选择", style="width: 120px")
        el-option(v-for="item in statusSelectAll", :key="item.value", :label="item.name", :value="item.value")
    //- el-form-item(label="提前预警时间")
    //-   el-input-number(v-model="warnDays", :controls="false", style="width: 80px")
    //-   span(style="margin-left: 8px") 天
    el-form-item
      el-button(type="primary", @click="searchSupplys") 搜索
    el-form-item
      el-button(type="primary", @click="resetSearch", plain) 重置
    el-form-item
      el-button(type="primary", @click="addLetter()", v-show="!letterList.length", plain) 初始化证书
  //- 列表
  .cl-common-table.cl-main-table
    el-table(
      :data="supplyList",
      highlight-current-row
      height="100%"
      size="mini"
      :row-class-name="tableRowClassName"
      @row-click="clickRoleRow"
      v-loading="loadingSupplys")
      el-table-column(align="center", show-overflow-tooltip, type="index", label="序号", :index="indexMethod", :fixed="true")
      el-table-column(align="center", show-overflow-tooltip, prop="id", label="编号")
      el-table-column(align="center", show-overflow-tooltip, prop="name", label="名称")
      el-table-column(align="center", show-overflow-tooltip, prop="vendorcategory", label="类别")
        template(slot-scope="scope")
          span {{ scope.row.vendorcategory | compare-list(vendorCateSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="vendorgrade", label="分级")
        template(slot-scope="scope")
          span {{ scope.row.vendorgrade | compare-list(vendorGradeSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="status", label="状态")
        template(slot-scope="scope")
          span {{ scope.row.status | compare-list(statusSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="mailingAddress", label="地址")
      el-table-column(align="center", show-overflow-tooltip, prop="createUser", label="创建人")
        template(slot-scope="scope")
          span {{ scope.row.createUser | compare-list(empSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="createTime", label="创建时间")
        template(slot-scope="scope")
          span {{ scope.row.createTime | date-format }}
      //- el-table-column(align="center", label="操作", min-width="90px")
      //-   template(slot-scope="scope")
      //-     el-tooltip(content="查看")
      //-       i.icon-act.el-icon-view(@click="viewSupply(scope.row)")
      //-     el-tooltip(content="编辑")
      //-       i.icon-act.el-icon-edit(@click="eidtSupply(scope.row, scope.$index)")
      //-     el-tooltip(content="删除")
      //-       i.icon-act.el-icon-delete(@click="deleteSupply(scope.row, scope.$index)")
  //- 分页
  el-pagination.cl-pagination(
    layout="total, prev, pager, next, jumper",
    @current-change="changeSupplyPage",
    :current-page.sync="currentPage",
    :page-size="pageSize",
    :total="supplyListTotal")
  .cl-common-table.cl-side-table
    el-table(
      :data="letterList",
      highlight-current-row
      height="100%"
      size="mini"
      v-loading="loadingLetters")
      el-table-column(align="center", show-overflow-tooltip, type="index", label="序号", :fixed="true")
      el-table-column(align="center", show-overflow-tooltip, prop="id", label="编号")
      el-table-column(align="center", show-overflow-tooltip, prop="name", label="名称")
        template(slot-scope="scope")
          el-input(v-model="scope.row.name", v-show="scope.row.isEdit")
          span(v-text="scope.row.name", v-show="!scope.row.isEdit")
      el-table-column(align="center", show-overflow-tooltip, prop="credentialType", label="证书类别")
        template(slot-scope="scope")
          el-input(v-model="scope.row.credentialType", v-show="scope.row.isEdit")
          span(v-text="scope.row.credentialType", v-show="!scope.row.isEdit")
      el-table-column(align="center", show-overflow-tooltip, prop="descr", label="描述")
        template(slot-scope="scope")
          el-input(v-model="scope.row.descr", v-show="scope.row.isEdit")
          span(v-text="scope.row.descr", v-show="!scope.row.isEdit")
      el-table-column(align="center", prop="issueDate", label="发证日期", min-width="96px")
        template(slot-scope="scope")
          el-date-picker(v-model="scope.row.issueDate", v-show="scope.row.isEdit", type="date" ,placeholder="选择日期", style="width: 100%", :clearable="false")
          span(v-show="!scope.row.isEdit") {{ scope.row.issueDate | date-locale }}
      el-table-column(align="center", prop="expireDate", label="到期日期", min-width="96px")
        template(slot-scope="scope")
          el-date-picker(v-model="scope.row.expireDate", v-show="scope.row.isEdit", type="date" ,placeholder="选择日期", style="width: 100%", :clearable="false")
          span(v-show="!scope.row.isEdit") {{ scope.row.expireDate | date-locale }}
      el-table-column(align="center", show-overflow-tooltip, prop="attachList", label="附件")
        template(slot-scope="scope")
          el-upload(
            :ref="`upload${scope.$index}`"
            v-show="scope.row.isEdit"
            action="https://jsonplaceholder.typicode.com/posts/"
            :limit="1"
            :show-file-list="false"
            :before-upload="uploadFileBefore"
            :on-success="uploadFileSucc"
            :on-error="uploadFileFail")
            i.el-icon-plus(@click="uploadFile(scope.$index)")
          a(v-if="scope.row.attachList && scope.row.attachList.length", v-show="!scope.row.isEdit", target="_blank", :href="scope.row.attachList[0].url") {{ scope.row.attachList[0].name }}
      el-table-column(align="center", show-overflow-tooltip, prop="remark", label="备注")
        template(slot-scope="scope")
          el-input(v-model="scope.row.remark", v-show="scope.row.isEdit")
          span(v-text="scope.row.remark", v-show="!scope.row.isEdit")
      el-table-column(align="center", label="操作", width="96px")
        template(slot-scope="scope")
          el-tooltip(content="编辑", v-show="!scope.row.isEdit")
            i.icon-act.el-icon-edit(@click="editLetter(scope.$index)")
          el-tooltip(content="添加", v-show="!scope.row.isEdit")
            i.icon-act.el-icon-plus(@click="addLetter(scope.$index)")
          el-tooltip(content="删除", v-show="!scope.row.isEdit")
            i.icon-act.el-icon-delete(@click="deleteLetter(scope.$index)")
          el-tooltip(content="确定", v-show="scope.row.isEdit")
            i.icon-act.el-icon-check(@click="insertLetter(scope.$index)")
          el-tooltip(content="取消", v-show="scope.row.isEdit")
            i.icon-act.el-icon-close(@click="cancleLetter(scope.$index)")

</template>

<script>
import { mapGetters } from 'vuex';
import ManApi from '@/api/manage';
import validate from '@/utils/validate';

const { isEmpty } = validate;

export default {
  name: 'creprovider',
  data() {
    return {
      // search
      providerCate: null,
      providerGrade: null,
      providerStatus: null,
      // table
      supplyList: [],
      supplyListTotal: 1,
      loadingSupplys: true,
      currentPage: 1,
      pageSize: 20,
      // 当前高亮ID
      highLightSupplyId: null,
      // list
      letterList: [],
      letterListBC: [],
      loadingLetters: false,
      statusSelect: [
        { name: '启用', value: '0' },
        { name: '禁用', value: '1' }
      ],
      statusSelectAll: [
        { name: '全部', value: null },
        { name: '启用', value: '0' },
        { name: '禁用', value: '1' }
      ]
    };
  },
  computed: {
    ...mapGetters(['empSelect', 'empSelectAll', 'vendorCateSelectAll', 'vendorGradeSelectAll', 'vendorCateSelect', 'vendorGradeSelect'])
  },
  methods: {
    indexMethod (i) {
      const size = this.pageSize || 20;
      return ((this.currentPage - 1) * size) + (i + 1);
    },
    resetSearch () {
      this.providerCate = null;
      this.providerGrade = null;
      this.providerStatus = null;
    },
    makeSearch () {
      const params = {};
      if (!isEmpty(this.providerCate)) {
        params.vendorcategory = this.providerCate;
      }
      if (!isEmpty(this.providerGrade)) {
        params.vendorgrade = this.providerGrade;
      }
      if (!isEmpty(this.providerStatus)) {
        params.status = this.providerStatus;
      }

      return params;
    },
    loadSupplyList (query) {
      const params = query || {};
      ManApi.getProviderList(params).then((result) => {
        if (!result.status) {
          this.supplyList = result.obj.records;
          this.supplyListTotal = result.obj.totalNum;
          if (this.supplyList.length) {
            this.highLightSupplyId = this.supplyList[0].id;

            this.loadingLetters = true;
            ManApi.getCredentialSupplyPerson({ id: this.highLightSupplyId }).then((rslObj) => {
              if (!rslObj.status) {
                this.letterList = rslObj.obj;
              }
              this.loadingLetters = false;
            }).catch(() => {
              this.loadingLetters = false;
            });
          } else {
            this.letterList = [];
          }
        } else {
          this.$message.error(result.comment);
        }
        this.loadingSupplys = false;
      }).catch((error) => {
        this.loadingSupplys = false;
        console.log(JSON.stringify(error));
      });
    },
    searchSupplys () {
      const params = this.makeSearch();
      this.loadingSupplys = true;

      this.loadSupplyList(params);
    },
    changeSupplyPage (currentPage) {
      const params = this.makeSearch();
      params.pageNum = currentPage;
      this.loadingSupplys = true;
      this.loadSupplyList(params);
    },
    // 选择供应商
    tableRowClassName ({ row }) {
      if (this.highLightSupplyId === row.id) {
        return 'focus-row';
      }

      return '';
    },
    clickRoleRow (supply) {
      this.highLightSupplyId = supply.id;

      this.loadingLetters = true;
      ManApi.getCredentialSupplyPerson({ id: this.highLightSupplyId }).then((rslObj) => {
        if (!rslObj.status) {
          this.letterList = rslObj.obj;
        }
        this.loadingLetters = false;
      }).catch(() => {
        this.loadingLetters = false;
      });
    },
    // 监听供应商证书列表
    addLetter (index) {
      const newObj = {
        isEdit: true,
        attachList: []
      };
      if (isEmpty(index)) {
        this.letterList.push(newObj);
      } else {
        this.letterList.splice((index + 1), 0, newObj);
      }
    },
    editLetter (index) {
      this.letterListBC[index] = JSON.parse(JSON.stringify(this.letterList[index]));
      this.$set(this.letterList[index], 'isEdit', true);
    },
    deleteLetter (index) {
      const register = this.letterList[index];
      if (register.id) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          ManApi.deleteCredentialLetter({ id: register.id }).then((res) => {
            if (res.status === 0) {
              this.letterList.splice(index, 1);
              this.letterListBC[index] = null;
              this.$message.success('删除成功');
            } else {
              this.$message.error(res.comment || '删除失败');
            }
          });
        }).catch(() => {
          this.$message.info('已取消删除');
        });
      } else {
        this.letterList.splice(index, 1);
        this.letterListBC[index] = null;
      }
    },
    insertLetter (index) {
      if (this.creditUrl) {
        const attach = this.letterList[index].attachList[0];
        if (!attach) {
          this.letterList[index].attachList[0] = {};
        }
        this.letterList[index].attachList[0].url = this.creditUrl;
        this.letterList[index].attachList[0].name = this.creditName;
      }

      this.letterList[index].vendorId = this.highLightSupplyId;
      ManApi.saveCredentialLetter(this.letterList[index]).then((result) => {
        if (!result.status) {
          this.$message.success('保存成功');
          if (!this.letterList[index].id) {
            this.letterList[index].id = result.obj;
          }
          this.letterList[index].isEdit = false;
        } else {
          this.$message.warning(result.comment);
        }
      });
    },
    cancleLetter (index) {
      if (this.letterListBC[index]) {
        this.$set(this.letterList, `${index}`, this.letterListBC[index]);
      } else {
        this.deleteLetter(index);
      }
    },
    // 附件上传
    uploadFile (index) {
      // 每次上传前清空上次文件
      this.$refs[`upload${index}`].clearFiles();
    },
    uploadFileBefore (file) {
      console.log(file);
      this.loading = this.$loading({
        fullscreen: true,
        text: '努力上传中, 请稍等...',
        background: 'transparent'
      });
    },
    uploadFileSucc (res, file) {
      if (file) {
        if (this.loading) {
          this.loading.close();
        }
        this.$message.success(`证书资质 ${file.name} 上传成功, 点击确认即可查看上传文件`);
        this.creditUrl = file.url;
        this.creditName = file.name;
      }
    },
    uploadFileFail (res, file) {
      if (file) {
        if (this.loading) {
          this.loading.close();
        }
        this.$message.warning(`证书资质 ${file.name} 上传失败, 请稍后再试`);
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next();
  },
  created () {
  },
  mounted () {
    this.loadSupplyList();
  }
};
</script>

<style lang="sass">
@import "../../../../styles/utils"
$SEARCHHEIGHT: 56px
$PAGEHEIGHT: 56px
.cp-credential-man-provider
  .cl-search
    height: $SEARCHHEIGHT
    overflow-x: auto
    overflow-y: hidden
    padding: 12px 0 12px 16px
    .el-form-item
      margin-right: 14px
    .el-form-item__label
      padding-right: 6px
  .cl-common-table
    position: absolute
    overflow: auto
    left: 16px
    right: 16px
    table
      &::before
        display: none
      .icon-act
        font-size: 16px
        margin-left: 3px
  .cl-main-table
    top: $SEARCHHEIGHT
    bottom: 240px
  .cl-pagination
    position: absolute
    bottom: 200px
    left: 0
    right: 0
    text-align: center
  .cl-side-table
    height: 160px
    bottom: 16px
  .el-table .focus-row td
    background: lightgoldenrodyellow
</style>
